//
// Created by Rory on 2020/10/16.
//

#ifndef DATA_STRUCTURE_PROGRAMMING_USING_C_STACK_H
#define DATA_STRUCTURE_PROGRAMMING_USING_C_STACK_H

#include "../common.h"

typedef struct stack__{
    int top;
    int capacity;
    int size;
    bool (*IsEmpty) (struct stack__*);
    void* (*pop) (struct stack__*);
    bool (*push) (struct stack__*, void*);
    void (*FreeStackData) (struct stack__*);
    void* data[STACK_CAPACITY];
} stack;


bool IsEmpty(stack* s){
    if(s->top != -1){
        return false;
    }
    return true;
}

void* pop(stack* s){
    if(!s->IsEmpty(s)){
        s->size -= 1;
        return s->data[s->top--];
    }
    return NULL;
}

bool push(stack* s, void* element){
    if(s->size == s->capacity){
        return false;
    }
    s->data[++s->top] = element;
    s->size += 1;
    return true;
}

void FreeStackData(stack* s){
    for (int i = 0; i < s->capacity; ++i) {
        if(s->data[i] != NULL){
            free(s->data[i]);
        }
    }
}

bool InitStack(stack* s){
    s->top = -1;
    s->capacity = STACK_CAPACITY;
    s->size = 0;
    s->IsEmpty = IsEmpty;
    s->pop = pop;
    s->push = push;
    s->FreeStackData = FreeStackData;
}

#endif //DATA_STRUCTURE_PROGRAMMING_USING_C_STACK_H
